﻿// -----------------------------------------------------------------------
//  <copyright file="MapsterModule.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2025 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2025-10-04 08:10</last-date>
// -----------------------------------------------------------------------

using DaprPlus.Mapster.Properties;

using OSharp.Localized;


namespace DaprPlus.Mapster;

[LocalizedDescription("String_Module_Mapster", typeof(ResMapster))]
public class MapsterModule : ModuleBase
{
    /// <summary>
    /// 获取 模块级别，级别越小越先启动
    /// </summary>
    public override ModuleLevel Level => ModuleLevel.Framework;

    /// <summary>
    /// 将模块服务添加到依赖注入服务容器中
    /// </summary>
    /// <param name="services">依赖注入服务容器</param>
    /// <returns></returns>
    public override IServiceCollection AddServices(IServiceCollection services)
    {
        services.AddSingleton<IMapTuple, MapFromAndMapToProfile>();

        return base.AddServices(services);
    }

    /// <summary>
    /// 应用模块服务
    /// </summary>
    /// <param name="provider">服务提供者</param>
    public override Task UseModule(IServiceProvider provider)
    {
        var logger = provider.GetLogger<MapsterModule>();

        var tuples = provider.GetServices<IMapTuple>().OrderBy(m => m.Order).ToArray();
        foreach (var mapTuple in tuples)
        {
            mapTuple.CreateMap();
            logger.LogInformation(ResMapster.Format_Init_Mapping_Pair, mapTuple.GetType());
        }
        TypeAdapterConfig.GlobalSettings.Compile();

        var mapper = new MapsterMapper();
        MapperExtensions.SetMapper(mapper);
        logger.LogInformation(ResMapster.Format_Init_Mapping_MapperExtensions, nameof(MapperExtensions));

        return base.UseModule(provider);
    }
}